// 引入
const handleBlogRouter = require("./src/router/blog");
const handleUserRouter = require("./src/router/user");
const querystring = require("querystring");


// 处理session
let SESSION_DATA = {};

const getPostData = (req) => {
  const promise = new Promise((resolve, reject) => {
    if (req.method !== "POST") {
      resolve({});
      return;
    }
    if (req.headers["content-type"] !== "application/json") {
      resolve({});
      return;
    }
    let postData = "";
    req.on("data", (chunk) => {
      postData += chunk.toString();
    });
    req.on("end", () => {
      if (!postData) {
        resolve({});
        return;
      }
      resolve(JSON.parse(postData));
    });
  });
  return promise;
};

const serverHandle = (req, res) => {

  // 设置返回格式
  res.setHeader("Content-Type", "application/json");
  const url = req.url;
  req.path = url.split("?")[0];
  req.query = querystring.parse(url.split("?")[1]);


  // 处理cookie
  // 'username=zhangsan;password=123'转化为json
  let cookieStr = {};
  let cookie = req.headers.cookie || "";
  // cookie.split(';'): ['username=zhangsan','password=123']
  cookie.split(";").forEach((item) => {
    // [['username','zhangsan'],['password','123']]
    const arr = item.split("=");
    const key = arr[0];
    const value = arr[1];
    cookieStr[key] = value;
  });
  req.cookie = cookieStr;

  // sesion处理
  let needSetCookie = false;
  let userid = req.cookie.userid;
  if (userid) {
    if (!SESSION_DATA[userid]) {
      SESSION_DATA[userid] = {};
    }
    req.session = SESSION_DATA;
  } else {
    // needSetCookie = true;
    SESSION_DATA = {}
    // 随机数不会重复
    userid = `${Date.now()}_${Math.random()}`;
    SESSION_DATA[userid] = {};
  }
  req.session = SESSION_DATA;
  // 处理postData
  getPostData(req).then((postData) => {
    req.body = postData;

    // 处理 blog 博客接口 
    const blogResult = handleBlogRouter(req, res, userid);
    if (blogResult) {

      blogResult.then((blogData) => {
        res.end(JSON.stringify(blogData));
      });
      return;
    }
    // 处理user登录接口
    const userResult = handleUserRouter(req, res, userid);

    if (userResult) {
      userResult.then((userData) => {
        res.end(JSON.stringify(userData));
      });
      return;
    }
    // 如果没有路由 返回显示的是 404
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.write("404 Not Found");
    res.end();
  });
};

// 向外暴漏
module.exports = serverHandle;
